package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     *
     * @param category
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody Category category) {
        log.info("category:{}", category);
        categoryService.save(category);
        return R.success("添加分类成功");
    }

    /**
     * 分页查询菜单表
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize) {
        Page<Category> dishPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.orderByDesc(Category::getSort);

        categoryService.page(dishPage, qw);

        return R.success(dishPage);
    }

    @DeleteMapping
    public R<String> delete(Long id) {
        //categoryService.removeById(id);
        categoryService.remove(id);
        return R.success("分类信息删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category) {

        categoryService.updateById(category);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        //创建条件构造器
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        //如果前端响应回来的type不为空,则根据type查询数据
        qw.eq(category.getType()!=null,Category::getType,category.getType());
        //然后用orderby进行排序,先按序号来升序,然后按修改时间来降序
        qw.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //调用业务层的list方法,获取到返回的数据
        List<Category> list = categoryService.list(qw);
        //返回结果
        return R.success(list);
    }

}
